package crp.core.workflow.domain.repositories;

import com.qwlabs.lang.C2;
import com.qwlabs.panache.Where;
import crp.core.shared.Tables;
import crp.core.workflow.domain.models.WorkflowInstanceEntity;
import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase;
import io.quarkus.panache.common.Parameters;

import javax.enterprise.context.ApplicationScoped;
import javax.persistence.Query;
import java.util.Collection;
import java.util.stream.Stream;

@ApplicationScoped
public class WorkflowInstanceRepository implements PanacheRepositoryBase<WorkflowInstanceEntity, String> {

    public Stream<WorkflowInstanceEntity> findByIds(Collection<String> ids) {
        if (C2.isEmpty(ids)) {
            return Stream.empty();
        }
        return find("id in (:ids)", Parameters.with("ids", ids)).stream();
    }

    public Stream<WorkflowInstanceEntity> findBy(Where where) {

        Query query = getEntityManager().createNativeQuery(String.format("select * from %s %s",
                        Tables.WORKFLOW_INSTANCE, where.getWithWhere()),
                WorkflowInstanceEntity.class);
        where.getParameters().forEach(query::setParameter);
        return query.getResultStream();
    }
}
